<template>
	<div class="purchaseGoods">
		<headerCom style="padding:0 28rpx" :searchShow="false" />
		<div class='mockArea' v-for="(item,index) in allTypeList" :key="item.label">
			<div class="goodsItem">
				<div class="headerPart">
					<div class='title'>{{item.label}}</div>
					<div class="icon">
						<image style="width: 100%; height:100%" src="../../static/purchaseGoods/icon.png" alt="" />
					</div>
				</div>
				<div style="display:flex;flex-direction: column;gap:24rpx">
					<div class='childItem' v-for="(i,k) in item.children" :key="i.label">
						<div style="margin-bottom: 20rpx;">
							<div class="childItemHeader">
								<div class='childName'>
									{{i.label}}
								</div>
								<div class='checkBox'>

									<checkbox :value="i.value" :disabled="!i.isShow" :checked="i.ischeck"
										borderColor="#151822" color="#fff" backgroundColor="#fff"
										activeBackgroundColor="#151822" activeBorderColor="#151822"
										style="transform:scale(0.7)" @click="checkParentBoxChange(i,k)" />
								</div>
							</div>
							<div class="groundData">
								<div class="basicInfo"> 共{{i.total}}件商品，共{{i.summary}}元</div>

								<div class="showMore" v-if='!i.isShow' @click="handleShowData(i)">
									展开
									<image class="icon" src="../../static/purchaseGoods/icon1.png" alt="" />
								</div>
								<div class="showMore" v-else @click="handleShowData(i)">
									收起
									<image class="icon" src="../../static/purchaseGoods/icon2.png" alt="" />
								</div>
							</div>
						</div>
						<checkbox-group >
							<div v-show='i.isShow'>
								<scroll-view class="scroll-view" style="height:618rpx;" :scroll-y="true" scroll-top="0"
									@scrolltolower='handleScrolltolower(i,1)' :scroll-with-animation="true">
									<div class='goodsList'>
										<div class='goodsListItem' v-for="(d,t) in i.goodsPageArr" :key="d.id">
											<div class="goodsItem-left">
												<div class="goodsMainImage">
													<image style="width:100%;height:100%" :src="d.imageUrl" alt="" />
												</div>
												<div class='goodsInfo'>
													<div class='title'>{{d.goodsName}}</div>
													<!-- <div class="appointments">已预约人数：{{d.saleCount}}人</div> -->
													<div class="price">{{d.sellPrice}}</div>
												</div>
											</div>
											<div class="goodsItem-right">
												<checkbox :value="d.id" :checked="d.ischeck" borderColor="#151822"
													color="#fff" backgroundColor="#fff" activeBackgroundColor="#151822"
													activeBorderColor="#151822" style="transform:scale(0.7)" @click="e=>checkChildrenBoxChange(e,d,t)"  />
											</div>
										</div>
									</div>
									<view class="pull-up-wrap" v-if="showPullUp">
										<view class="load-view">
											<view class="pull-up-animation" v-if="loading"
												:style="[pullUpAnimationStyle]"></view>
											<text class="pull-up-text"
												:style="[pullUpTextStyle]">{{ loadStateText }}</text>
										</view>
									</view>
								</scroll-view>
							</div>
						</checkbox-group>
					</div>
				</div>
			</div>
		</div>

		<div class='btn' v-if="sureBtnShow" @click="handleSurePopup">
			确定
		</div>

		<uni-popup ref="popup" :mask-click="false">
			<div class='popup relative'>
				<div class='tipIcon absolute'>
					<image src="../../static/purchaseGoods/tipIcon.png" style="width: 100%;" alt="" />
				</div>
				<div class="close absolute" @click="handleClosePopup">
					<image src="../../static/purchaseGoods/close.png" style="width: 100%;" alt="" />
				</div>
				<div class='title'>温馨提示</div>
				<div class='content'>
					您已选中{{accountNum.length}}件商品，共计{{allPrice}}元，请选择付款方式
				</div>
				<div class="btnGroup">
					<div class="btn1" @tap="addCart">预付款</div>
					<div class="btn2" @tap="pay">去付款</div>
				</div>
			</div>
		</uni-popup>



		<subTabbar />
	</div>
</template>

<script>
	import {
		getAllTypeList,
		purchaseGoodsPage,
		batchAddGoodsToCart
	} from "../../api/api.js"
	import scrollList from "../../components/scroll-list/scroll-list.vue"
	import subTabbar from "../../components/basicComponent/subTabbar.vue"
	import headerCom from "../../components/basicComponent/market/headerCom.vue"
	export default {
		name: 'purchaseGoods',
		components: {
			headerCom,
			subTabbar,
			scrollList
		},
		data() {
			return {
				allTypeList: [],
				option: {
					auto: false,
				},
				query: {
					secondCategoryId: '',
					pageNum: 1,
					pageSize: 20,
				},
				listWrapStyle: {
					height: '618rpx'
				},
				showPullUp: false, // 是否显示上拉加载
				loading: false, // 是否加载中
				loadStateText: '正在加载中~', // 加载状态文字
				accountNum:[],
				allPrice:0,
			}
		},
		watch: {
			
		},
		computed:{
			sureBtnShow(){
				let totalPrice = 0; // 初始化总价格
				let selectedIds = []; // 用于存储选中商品的 ID
				
				this.allTypeList.forEach(item => {
				    item.children.forEach(i => {
				        // 直接累加选中商品的价格和 ID
				        i.goodsPageArr?.forEach(j => {
				            if (j.ischeck) {
				                totalPrice += j.sellPrice; // 累加价格
				                selectedIds.push(j.id); // 收集选中商品的 ID
				            }
				        });
				    });
				});
				
				// 输出总价格和选中商品的 ID
				console.log("总价格:", totalPrice);
				console.log("选中商品 ID:", selectedIds);
				this.accountNum=selectedIds
				this.allPrice=totalPrice
				if(selectedIds.length!=0){
					return true
				}
				return false
			}
		},
		mounted() {
			this.getAllType()
		},
		methods: {
			handleSurePopup() {
				
				// let totalPrice = 0; // 初始化总价格
				// let selectedIds = []; // 用于存储选中商品的 ID
				
				// this.allTypeList.forEach(item => {
				//     item.children.forEach(i => {
				//         // 直接累加选中商品的价格和 ID
				//         i.goodsPageArr?.forEach(j => {
				//             if (j.ischeck) {
				//                 totalPrice += j.sellPrice; // 累加价格
				//                 selectedIds.push(j.id); // 收集选中商品的 ID
				//             }
				//         });
				//     });
				// });
				
				// // 输出总价格和选中商品的 ID
				// console.log("总价格:", totalPrice);
				// console.log("选中商品 ID:", selectedIds);
				// this.accountNum=selectedIds
				// this.allPrice=totalPrice
				if(this.accountNum.length==0){
					uni.showToast({
						title:'请选择商品',
						icon:'none'
					})
					return
				}
				
				this.$refs.popup.open('center')
				
				console.log()
				
			},
			handleClosePopup() {
				this.$refs.popup.close()
			},
			// 16进制转RGB
			hexToRgb(hex) {
				const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
				hex = hex.replace(shorthandRegex, (m, r, g, b) => {
					return r + r + g + g + b + b;
				});
				const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
				return result ? {
						r: parseInt(result[1], 16),
						g: parseInt(result[2], 16),
						b: parseInt(result[3], 16)
					} :
					null;
			},
			// 上拉中动画样式
			pullUpAnimationStyle() {
				const style = {};
				const {
					r,
					g,
					b
				} = this.hexToRgb("#82848a");
				style.borderColor = `rgba(${r},${g},${b},0.2)`;
				style.borderTopColor = '#82848’';
				return style;
			},
			// 上拉中文字样式
			pullUpTextStyle() {
				const style = {};
				style.color = '#82848a';
				return style;
			},
			handleShowData(item) {

				this.query.secondCategoryId = item.value
				item.isShow = !item.isShow
				if (item.goodsPageArr.length != 0) return
				this.getPurchaseGoodsPage(item, 1)

			},
			checkChildrenBoxChange(e,i, k) {
				i.ischeck = !i.ischeck
				// let arr = e.target.value
				// item['selectArr'] = quitArr.map(item => item.id)
				// i['selectArr'] = [...new Set([...i.selectArr, ...arr])]
			},
			checkParentBoxChange( item, index) {
				// item 父级  index 子下标
				
				let quitArr = item.goodsPageArr.slice(0, 10)
				quitArr.map(item => item.ischeck = true)
				item['selectArr'] = quitArr.map(item => item.id)
				console.log(item)

			},
			getAllType() {
				getAllTypeList().then(res => {
					console.log('getAllTypeList', res)
					if (res.code == 200) {
						res.data.map(item => {
							item.value = item.value + ''
							item.children.map(item => {
								item.goodsPageArr = []
								item.ischeck = false;
								item.isShow = false
							})
						})
						this.allTypeList = res.data
					} else {
						this.allTypeList = []
					}
				})
			},

			handleScrolltolower(item, index) {
				if (!this.showPullUp && !this.loading && item.total != item.goodsPageArr.length) {
					console.log('滚动到底部了', item, index)
					this.showPullUp = true
					this.loading = true
					this.getPurchaseGoodsPage(item, 1)
				}


			},

			// 获取商品
			getPurchaseGoodsPage(item, index) {
				console.log('item', item)

				// 如果 item 中存在 query 参数,则用query的参数入参
				let query = item.query ? item.query : JSON.parse(JSON.stringify(this.query))
				if (index == 2) {
					this.query.pageNum = 1
				}
				purchaseGoodsPage(query).then(res => {
					console.log('purchaseGoodsPage', res)

					if (res.code == 200) {
						res.data.records.map(item => {
							item.ischeck = false
						})
						if (index == 1) {
							// 加载
							query.pageNum++;
							// 拷贝
							let copyQuery =
								item['goodsPageArr'] = [...item.goodsPageArr, ...res.data.records]
							item['total'] = res.data.total
							item['selectArr'] = []
							item['query'] = query
						} else {
							// 刷新
							item['goodsPageArr'] = res.data.records
							item['total'] = res.data.total
							item['selectArr'] = []
							item['query'] = query
						}


						setTimeout(() => {
							this.showPullUp = false
							this.loading = false
						}, 500)
					} else {

						item['goodsPageArr'] = []
					}
				})
			},
			
			// 加入购物车
			addCart() {
				let data = {
					goodsIds:this.accountNum.join(',')
				}
				batchAddGoodsToCart(data).then( res => {
					if( res.code == 200 ) {
						uni.showToast({
							title:'加入购物车成功',
							icon:'none'
						})
						this.$refs.popup.close()
					}
				})
			},
			
			// 去结算
			pay() {
				uni.navigateTo({
					url:'../goods/catSubmitOrder?cartIds=' + this.accountNum.join(',') + '&isPurchase=1'
				})
			}
		}
	}
</script>

<style scoped lang="less">
	.purchaseGoods {
		position: relative;
		padding: 180rpx 0rpx 180rpx 0rpx;
		box-sizing: border-box;


	}

	.popup {
		width: 616rpx;
		height: 470rpx;
		background: #FFFFFF;
		border-radius: 16rpx;
		padding: 112rpx 40rpx 40rpx 40rpx;
		box-sizing: border-box;
		
	}
	.popup .content {
		font-weight: 400;
		font-size: 32rpx;
		color: #151822;
		margin-top: 24rpx;
		text-align: center;
		line-height: 60rpx;
		margin-bottom: 52rpx;
	}
	
	.popup .btnGroup {
		display: flex;
		gap: 24rpx;
	
		.btn1 {
			width: 256rpx;
			height: 90rpx;
			background: #F8F8F8;
			border-radius: 16rpx;
			font-weight: 500;
			font-size: 32rpx;
			color: #151822;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	
		.btn2 {
			width: 256rpx;
			height: 90rpx;
			background: var(--tm-themeColor-level1);
			border-radius: 16rpx;
			font-weight: 500;
			font-size: 32rpx;
			color: #151822;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
	
	.popup .close {
		width: 48rpx;
		height: 48rpx;
		top: 28rpx;
		right: 28rpx
	}
	
	.popup .tipIcon {
		width: 128rpx;
		height: 128rpx;
		top: -64rpx;
		left: 50%;
		right: 50%;
		transform: translateX(-50%);
	}
	
	.popup .title {
		font-weight: 500;
		font-size: 40rpx;
		color: #0F1724;
		text-align: center;
	}
	
	.btn {
		width: 128rpx;
		height: 128rpx;
		background: url("../../static/purchaseGoods/btn.png") no-repeat;
		background-size: 100% 100%;
		position: fixed;
		right: 28rpx;
		bottom: 140rpx;
		font-weight: 600;
		font-size: 32rpx;
		color: #151822;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	

	

	.goodsItem {
		width: 100%;
		height: auto;
		min-height: 296rpx;
		background: url("../../static/purchaseGoods/bg.png") no-repeat;
		background-size: 100%;
		padding: 0 28rpx;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		margin-top: 40rpx;
		gap: 20rpx;

		.headerPart {
			width: 100%;
			display: flex;
			height: 100rpx;
			margin-bottom: 20rpx;

			.title {
				width: 316rpx;
				font-weight: 600;
				font-size: 44rpx;
				color: #151822;
				display: flex;
				justify-content: start;
				align-items: center;
				padding-left: 20rpx;
				box-sizing: border-box;
			}

			.icon {
				width: 150rpx;
				height: 52rpx;
				margin-top: 20rpx;
			}
		}

		.childItem {
			width: 100%;
			background: #FFFFFF;
			box-shadow: 0px 4rpx 12rpx 0px rgba(0, 0, 0, 0.06);
			border-radius: 24rpx;
			padding: 28rpx 40rpx;
			box-sizing: border-box;

			.goodsList {

				display: flex;
				flex-direction: column;
				gap: 20rpx;

				.goodsListItem {
					display: flex;

					.goodsItem-left {
						display: flex;

						.goodsMainImage {
							min-width: 172rpx;
							height: 172rpx;
							border-radius: 18rpx;
							overflow: hidden;
							margin-right: 20rpx;
						}

						.goodsInfo {
							width: 362rpx;
							display: flex;
							flex-direction: column;
							gap: 20rpx;

							.title {
								font-weight: 500;
								font-size: 24rpx;
								color: #0F1724;
								overflow: hidden;
								text-overflow: ellipsis;
								display: -webkit-box;
								-webkit-box-orient: vertical;
								-webkit-line-clamp: 2;
								line-height: 30rpx;
							}

							.appointments {
								font-weight: 400;
								font-size: 24rpx;
								color: rgba(21, 24, 34, 0.8);
							}

							.price {
								font-weight: bold;
								font-size: 36rpx;
								color: #151822;

							}

							// .price::before {
							// 	content: '¥';
							// 	font-weight: bold;
							// 	font-size: 24rpx;
							// 	color: #151822;
							// }
						}

					}

					.goodsItem-right {
						display: flex;
						justify-content: center;
						align-items: center;
						padding-left: 28rpx;
						box-sizing: border-box;
					}
				}
			}

			.childItemHeader {
				width: 100%;

				display: flex;
				justify-content: space-between;

				.childName {
					font-weight: 500;
					font-size: 36rpx;
					color: #151822;
				}
			}

			.groundData {
				margin-top: 24rpx;
				display: flex;
				justify-content: space-between;

				.basicInfo {
					font-weight: 400;
					font-size: 28rpx;
					color: #898A8F;
				}

				.showMore {
					font-weight: 400;
					font-size: 28rpx;
					color: #898A8F;
					display: flex;
					align-items: center;

					.icon {
						width: 36rpx;
						height: 36rpx;
					}
				}
			}

		}

		.pull-up-wrap {
			display: flex;
			align-items: center;
			justify-content: center;

			.load-view {
				padding: 20rpx 0;
				display: flex;
				align-items: center;
				justify-content: center;

				.pull-up-animation {
					width: 32rpx;
					height: 32rpx;
					border-width: 4rpx;
					border-style: solid;
					border-radius: 50%;
					animation: spin 0.5s linear infinite;
				}

				.pull-up-text {
					margin-left: 10rpx;
				}
			}
		}


	}
</style>